#ifndef __VIDEO_H__
#define __VIDEO_H__

#include <queue>
#include <mutex>

#include <QImage>
#include <QPixmap>
#include <QMutex>
#include <QMutexLocker>
#include <QDebug>
#include <QThread>

#include <opencv2/opencv.hpp>

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>

#include <time.h>
}

struct MatWrapper {
    cv::Mat mat;
    int id;
};

struct VideoMuxPacket {
    AVPacket* av_packet = NULL;
    AVCodecParameters* video_codec_param = NULL;
};

class VideoStreamThread : public QThread
{
    Q_OBJECT

public:
    cv::VideoCapture m_cap;
    std::string m_url;
    QMutex m_mutex;
    //bool m_need_save;
    bool m_video_mux_stop;
    bool m_stop;
    int m_id;

    // TODO: frame rate

    explicit VideoStreamThread(std::string url, int id = 0, QObject *parent = nullptr) :
        QThread(parent), m_stop(false), m_video_mux_stop(true), m_url(url), m_id(id) {}
    ~VideoStreamThread() {
        //save_stop();
        video_mux_stop();
        stop();
        this->quit();
        this->wait();
    }

    //void save_start();
    //void save_stop();

    void video_mux_start();
    void video_mux_stop();

    void run();

    void stop() {
        // TODO: remove?
        QMutexLocker locker(&m_mutex);
        m_stop = true;
    }

private slots:

private:
	int64_t video_pts = -1;
};

cv::Mat cv_pic_get_demo();
int cv_test_demo();
int rtsp_test();
int rtsp_test_demo();

extern std::queue<MatWrapper> img_queue; // 图像队列
extern std::mutex queue_mutex;          // 队列互斥锁
extern std::condition_variable pic_cond;     // 条件变量

extern std::queue<VideoMuxPacket> g_video_mux_packet_queue[4]; // 视频队列
//extern std::queue<AVPacket*> g_video_mux_packet_queue[4]; // 视频队列
extern std::mutex g_video_mux_packet_queue_mutex[4];          // 队列互斥锁
extern std::condition_variable g_video_mux_packet_queue_cv[4];     // 条件变量

#endif // __VIDEO_H__
